<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="字典编号" prop="dictCode">
              <el-input v-model="queryParams.dictCode" placeholder="请输入字典编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="父code" prop="parentCode">
              <el-input v-model="queryParams.parentCode" placeholder="请输入父code" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="字典名称" prop="dictLabel">
              <el-input v-model="queryParams.dictLabel" placeholder="请输入字典名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="字典键值" prop="dictValue">
              <el-input v-model="queryParams.dictValue" placeholder="请输入字典键值" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="审核" prop="visible">
              <el-select v-model="queryParams.visible" placeholder="请选择审核" clearable>
                <el-option v-for="dict in ywsf" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:multiDict:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="multiDictTableRef"
        v-loading="loading"
        :data="multiDictList"
        row-key="dictCode"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="字典编号" prop="dictCode" />
        <el-table-column label="父code" align="center" prop="parentCode" />
        <el-table-column label="字典名称" align="center" prop="dictLabel" />
        <el-table-column label="字典键值" align="center" prop="dictValue" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="审核" align="center" prop="visible">
          <template #default="scope">
            <dict-tag :options="ywsf" :value="scope.row.visible" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['business:multiDict:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button v-hasPermi="['business:multiDict:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['business:multiDict:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改多级字典对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="multiDictFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父code" prop="parentCode">
          <el-tree-select
            v-model="form.parentCode"
            :data="multiDictOptions"
            :props="{ value: 'dictCode', label: 'dictLabel', children: 'children' }"
            value-key="dictCode"
            placeholder="请选择父code"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="字典名称" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入字典键值" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="审核" prop="visible">
          <el-radio-group v-model="form.visible">
            <el-radio v-for="dict in ywsf" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MultiDict" lang="ts">
import { listMultiDict, getMultiDict, delMultiDict, addMultiDict, updateMultiDict } from '@/api/business/multiDict';
import { MultiDictVO, MultiDictQuery, MultiDictForm } from '@/api/business/multiDict/types';

type MultiDictOption = {
  dictCode: number;
  dictLabel: string;
  children?: MultiDictOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { ywsf } = toRefs<any>(proxy?.useDict('ywsf'));

const multiDictList = ref<MultiDictVO[]>([]);
const multiDictOptions = ref<MultiDictOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const multiDictFormRef = ref<ElFormInstance>();
const multiDictTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MultiDictForm = {
  baseId: undefined,
  parentCode: undefined,
  dictLabel: undefined,
  dictValue: undefined,
  sort: undefined,
  visible: true
};

const data = reactive<PageData<MultiDictForm, MultiDictQuery>>({
  form: { ...initFormData },
  queryParams: {
    dictCode: undefined,
    parentCode: undefined,
    dictLabel: undefined,
    dictValue: undefined,
    visible: undefined,
    params: {}
  },
  rules: {
    baseId: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    parentCode: [{ required: true, message: '父code不能为空', trigger: 'blur' }],
    dictLabel: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
    visible: [{ required: true, message: '审核不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询多级字典列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMultiDict(queryParams.value);
  const data = proxy?.handleTree<MultiDictVO>(res.data, 'dictCode', 'parentCode');
  if (data) {
    multiDictList.value = data;
    loading.value = false;
  }
};

/** 查询多级字典下拉树结构 */
const getTreeselect = async () => {
  const res = await listMultiDict();
  multiDictOptions.value = [];
  const data: MultiDictOption = { dictCode: 0, dictLabel: '顶级节点', children: [] };
  data.children = proxy?.handleTree<MultiDictOption>(res.data, 'dictCode', 'parentCode');
  multiDictOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  multiDictFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: MultiDictVO) => {
  reset();
  getTreeselect();
  if (row != null && row.dictCode) {
    form.value.parentCode = row.dictCode;
  } else {
    form.value.parentCode = 0;
  }
  dialog.visible = true;
  dialog.title = '添加多级字典';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(multiDictList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: MultiDictVO[], status: boolean) => {
  data.forEach((item) => {
    multiDictTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: MultiDictVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentCode = row.parentCode;
  }
  const res = await getMultiDict(row.baseId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改多级字典';
};

/** 提交按钮 */
const submitForm = () => {
  multiDictFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.baseId) {
        await updateMultiDict(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMultiDict(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: MultiDictVO) => {
  await proxy?.$modal.confirm('是否确认删除多级字典编号为"' + row.baseId + '"的数据项？');
  loading.value = true;
  await delMultiDict(row.baseId).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>
